from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
from django.views import View
import json
from django import http
from django_redis import get_redis_connection
from .models import User
from iHome.utils.views import LoginJsonRequiredMixin
from django.conf import settings
from iHome.utils.upload_pictures import upload_pictures
import re


# Create your views here.
class AttestationView(LoginJsonRequiredMixin, View):
    def get(self, request):
        # 发布房源,获取实名信息
        user = request.user
        data = {'real_name': user.real_name, 'id_card': user.id_card}
        return http.JsonResponse({'errno': "0", 'errmsg': 'ok', 'data': data})

    def post(self, request):
        # 实名认证
        json_dict = json.loads(request.body.decode())
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')
        if not all([real_name, id_card]):
            return http.JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})
        if not re.match('[\u4e00-\u9fa5]{2,15}', real_name):
            return http.JsonResponse({'errno': 4103, 'errmsg': '参数real_name有误'})
        if not re.match(r'^[1-8][1-7]\d{4}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dX]$', id_card):
            return http.JsonResponse({'errno': 4103, 'errmsg': '参数id_card有误'})
        user = request.user
        user.real_name = real_name
        user.id_card = id_card
        user.save()
        data = {'real_name': real_name, 'id_card': id_card}
        return http.JsonResponse({'errno': 0, 'errmsg': '认证信息保存成功', 'data': data})


class PutUsernameView(LoginJsonRequiredMixin, View):
    def put(self, request):
        # 修改用户名
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')
        if not name:
            return http.JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})
        user = request.user
        user.username = name
        user.save()
        return http.JsonResponse({'errno': 0, 'errmsg': '修改成功'})


class UserAvatarView(LoginJsonRequiredMixin, View):
    def post(self, request):
        # 上传头像
        data = request.FILES.get('avatar').read()
        if not data:
            return http.JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})
        # image = data.file.getvalue()
        ret, info = upload_pictures(data)
        url = settings.AVATAR_URL + ret['key']
        user = request.user
        user.avatar = url
        user.save()
        data = {'avatar_url': url}
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})


class UserInfoView(LoginJsonRequiredMixin, View):
    def get(self, request):
        # 用户中心
        user_id = request.user.id
        try:
            user = User.objects.get(id=user_id)
        except:
            return http.JsonResponse({"errno": 4001, "errmsg": '数据库查询错误'})
        avatar = user.avatar
        if avatar:
            avatar = str(user.avatar)
        else:
            avatar = None
        data = {
            "avatar_url": avatar,
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})


class LoginView(View):
    def delete(self, request):
        logout(request)
        return http.JsonResponse({"errno": "0", "errmsg": '已登出'})

    def get(self, request):
        if request.user.is_authenticated:
            user = request.user
            return http.JsonResponse(
                {"errno": "0", "errmsg": "已登录", "data": {"name": user.username, 'user_id': user.id}})
        else:
            return http.JsonResponse(
                {"errno": 4101, "errmsg": "未登录"})

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        if not all([mobile, password]):
            return http.JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'errno': 4102, 'errmsg': 'password格式有误'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4102, 'errmsg': 'mobile格式有误'})
        User.USERNAME_FIELD = 'mobile'

        user = authenticate(request=request, username=mobile, password=password)
        if not user:
            return http.JsonResponse({'errno': '4102', 'errmsg': '账号或密码错误'})
        login(request, user)
        return http.JsonResponse({"errno": "0", "errmsg": "登录成功"})


class RegisterView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        phonecode = json_dict.get('phonecode')
        password = json_dict.get('password')
        if not all([mobile, phonecode, password]):
            return http.JsonResponse({'errno': '4103', 'errmsg': '缺少必传参数'})
        if not re.match(r'', mobile):
            return http.JsonResponse({'errno': '4103', 'errmsg': 'mobile格式有误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'errno': '4103', 'errmsg': 'password格式有误'})
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({'errno': '4002', 'errmsg': '短信验证码失效'})

        if phonecode != sms_code_server.decode():
            return http.JsonResponse({'errno': '4103', 'errmsg': '短信验证码有误'})
        # try:
        User.objects.create_user(
            username=mobile,
            password=password,
            mobile=mobile,
        )
        # except:
        #     return http.JsonResponse({'errno': '4001', 'errmsg': '注册失败'})
        response = http.JsonResponse({'errno': 0, 'errmsg': '注册成功'})
        return response
